﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Husb.Util;
using Husb.Util.Enum;
using CentralOffice.Admin.Data;
using CentralOffice.Task.BusinessActions;
using CentralOffice.Task.Data;

using ProcessTable = CentralOffice.Admin.Data.ApprovalProcessDataSet.ApprovalProcessDataTable;
using ProcessRow = CentralOffice.Admin.Data.ApprovalProcessDataSet.ApprovalProcessRow;
using StepTable = CentralOffice.Admin.Data.ApprovalStepDataSet.ApprovalStepDataTable;
using StepRow = CentralOffice.Admin.Data.ApprovalStepDataSet.ApprovalStepRow;

using ApplicationTable = CentralOffice.Task.Data.ApplicationDataSet.ApplicationsDataTable;
using ApplicationRow = CentralOffice.Task.Data.ApplicationDataSet.ApplicationsRow;

using ApprovalTable = CentralOffice.Task.Data.ApprovalDataSet.ApprovalsDataTable;
using ApprovalRow = CentralOffice.Task.Data.ApprovalDataSet.ApprovalsRow;


namespace CentralOffice.WebClient.Tasks
{
    public partial class ApplicationEditPre : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                SiteUtil.PopulateListBox(ddlCategory, SiteConstants.ApprovalObject, false);
                ddlCategory.SelectedIndex = 0;

                PopulateProcess(Int32.Parse(ddlCategory.SelectedValue));

                txtApplicationCode.Text = Applications.GetMaxApplicationCode(DateTime.Now);
                lblApplicant.Text = CommonUtil.TrimAll(ApplicationContext.ActualUserName);

                string id = HttpContext.Current.Request.QueryString["id"];
                if (!String.IsNullOrEmpty(id))
                {
                    SetFields(id);

                    ddlCategory_SelectedIndexChanged(null, new EventArgs());

                    ddlProcess_SelectedIndexChanged(null, new EventArgs());

                    UpdatePanel3.Update();
                    upStep.Update();

                }
            }

            //PopulateProcess(Int32.Parse(ddlCategory.SelectedValue));

        }

        private void SetFields(string applicationId)
        {
            ApplicationRow application = CentralOffice.Task.BusinessActions.Applications.GetById(new Guid(applicationId));

            ddlCategory.SelectedValue = application.Category.ToString();//EnumUtil.GetInt32(SiteConstants.TaskPriority, CategoryDataSourceType.Xml, application.Status).ToString();

            ddlProcess.SelectedValue = application.ProcessId.ToString();

            //txtId.Text = application.Id;
            txtApplicationCode.Text = application.IsApplicationCodeNull() ? "" : application.ApplicationCode;
            txtName.Text = application.Name;
            //txtCategory.Text = application.Category;
            
            //ddlUrgencyDegree.SelectedValue = application.UrgencyDegree.ToString();
            //txtDateOfApplication.Text = application.DateOfApplication.ToString("yyyy-MM-dd");
            //txtApplicantReadOnly.Value = application.Applicant;
            //txtApplicant.Value = application.Applicant;
            lblApplicant.Text = application.Applicant;
            txtContentText.Text = application.ApprovalContent;
            //txtStatus.Text = application.Status;

            //txtDescription.Text = application.Description;
            //ApprovalRow approval = CentralOffice.Task.BusinessActions.Approvals.GetFirstReply(application.Id);
            //txtApprovedBy.Value = approval.ApprovedBy;
            //txtApprovedByReadOnly.Value = approval.ApprovedBy;
            //txtApprovalContent.Text = approval.ContentText;
            //chkIsFinal.Checked = approval.IsFinal;

            txtExecutor.Text = application.IsApplicationExecutorNull() ? "" : application.ApplicationExecutor;
            //txtExecutorReadOnly.Value = txtExecutor.Value;

            
            if (!application.IsAttachmentsNull() && application.Attachments.Length > 0)
            {
                lblAttachments.Text = "<br />" + application.Attachments.Substring(application.Attachments.LastIndexOf(System.IO.Path.AltDirectorySeparatorChar) + 1);
                //lblElectricalBlueprint.NavigateUrl = archive.ElectricalBlueprint;
                lblAttachments.Visible = true;
            }

            //ProcessTable processes = CentralOffice.Admin.BusinessActions.ApprovalProcess.GetProcessBySubject(Int32.Parse(ddlCategory.SelectedValue));

            
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string applicationId = HttpContext.Current.Request.QueryString["id"];

            if (String.IsNullOrEmpty(applicationId) && txtApplicationCode.Text.Trim().Length > 0)
            {
                bool exist = CentralOffice.Task.BusinessActions.Applications.IsExistApplicationCode(txtApplicationCode.Text.Trim());
                if (exist)
                {
                    lblJavaScript.Text = "<script type=\"text/javascript\">alert('申请编号已存在，请修改！');</script>";
                    return;
                }
            }

            ApprovalDataSet approvalDataSet;

            ApplicationDataSet applicationDataSet = GetFields(applicationId, out approvalDataSet);

            CentralOffice.Task.BusinessActions.Applications.Update(applicationDataSet, approvalDataSet);

            if (String.IsNullOrEmpty(applicationId))
            {
                applicationId = (applicationDataSet.Applications.Rows[0] as ApplicationRow).Id.ToString();
            }

            Response.Redirect("ApplicationView.aspx?id=" + applicationId.ToString());

        }

        private ApplicationDataSet GetFields(string applicationId, out ApprovalDataSet approvalDataSet)
        {
            ApplicationDataSet applicationDataSet = null;
            ApplicationRow application = null;

            approvalDataSet = new ApprovalDataSet();

            ProcessRow process = CentralOffice.Admin.BusinessActions.ApprovalProcess.GetByIdFromCache(new Guid(ddlProcess.SelectedValue));
            StepTable steps = CentralOffice.Admin.BusinessActions.ApprovalStep.GetStepByProcessId(new Guid(ddlProcess.SelectedValue));

            if (String.IsNullOrEmpty(applicationId))
            {
                // new
                applicationDataSet = new ApplicationDataSet();
                application = applicationDataSet.Applications.NewApplicationsRow();
                SiteUtil.PopulateCommonField(application, Guid.NewGuid());
                application.Status = 1;//EnumUtil.GetInt32(SiteConstants.TaskPriority, CategoryDataSourceType.Xml, application.Status);
                //application.Applicant = txtApplicant.Value.Trim(SiteConstants.CommonSeparatorChar);

                AddApprovalSteps(approvalDataSet, application.Id, process, steps);
            }
            else
            {
                // update
                application = CentralOffice.Task.BusinessActions.Applications.GetById(new Guid(applicationId));

                //ApprovalRow approval = CentralOffice.Task.BusinessActions.Approvals.GetFirstReply(new Guid(Request.QueryString["id"]));
                //approvalDataSet = approval.Table.DataSet as ApprovalDataSet;
                int rejection = EnumUtil.GetInt32(SiteConstants.ApprovalStatus, CategoryDataSourceType.Xml, "否决");
                // 如果是修改否决的申请，删除原来的审批步骤，并生成新的审批步骤
                if (application.Status == rejection)
                {
                    //ApprovalRow rejected = CentralOffice.Task.BusinessActions.Approvals.GetRejectedStep(new Guid(Request.QueryString["id"]));
                    //AddApprovalRow(approvalDataSet, application.Id, Int32.Parse(ddlUrgencyDegree.SelectedValue), rejected.ApprovedBy, txtApprovalContent.Text, chkIsFinal.Checked);
                    // 如果是修改否决的申请，修改申请状态

                    CentralOffice.Task.BusinessActions.Approvals.DeleteByApplicationId(new Guid(applicationId));
                    application.Status = EnumUtil.GetInt32(SiteConstants.ApprovalStatus, CategoryDataSourceType.Xml, "待审");
                }
                else
                {
                    // 修改第一个审批步骤的信息
                    //approval.ApprovedBy = txtApprovedBy.Value;//, , 
                    //approval.ContentText = txtApprovalContent.Text;
                    //approval.IsFinal = chkIsFinal.Checked;

                    //if (approval.IsNextStepIsApprovedNull())
                    //{
                    //    approval.NextStepIsApproved = false;
                    //}
                    //if (approval.IsSequenceNumberNull())
                    //{
                    //    approval.SequenceNumber = 1;
                    //}
                }


                CentralOffice.Task.BusinessActions.Approvals.DeleteByApplicationId(new Guid(applicationId));
                AddApprovalSteps(approvalDataSet, application.Id, process, steps);

                applicationDataSet = application.Table.DataSet as ApplicationDataSet;
            }

            application.ProcessId = process.Id;

            application.ApplicationCode = txtApplicationCode.Text;
            application.Name = txtName.Text;
            application.Category = Int32.Parse(ddlCategory.SelectedValue);
            application.UrgencyDegree = process.UrgencyDegree;// Int32.Parse(ddlUrgencyDegree.SelectedValue);

            //application.DateOfApplication = txtDateOfApplication.Text.Length == 0 ? DateTime.Now : DateTime.Parse(txtDateOfApplication.Text).AddHours(DateTime.Now.Hour).AddMinutes(DateTime.Now.Minute).AddSeconds(DateTime.Now.Second);
            application.DateOfApplication = DateTime.Now;
            //application.Applicant = txtApplicant.Value.Trim(SiteConstants.CommonSeparatorChar);
            application.Applicant = CommonUtil.TrimAll(ApplicationContext.ActualUserName);
            application.ApprovalContent = txtContentText.Text;// process.Name;// txtApprovalContent.Text;
            application.ApplicationExecutor = process.Executor;// txtExecutor.Value;

            string fileName = SaveFile(SiteUtil.GetTaskFilesPath(), fileAttachments);
            if (fileName.Length > 0)
            {
                application.Attachments = fileName;
            }

            if (String.IsNullOrEmpty(applicationId))
            {
                applicationDataSet.Applications.AddApplicationsRow(application);
            }

            return applicationDataSet;
        }

        protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtExecutor.Text = "";
            //int approvalObject = EnumUtil.GetInt32(SiteConstants.ApprovalObject, CategoryDataSourceType.Xml, ddlCategory.SelectedValue)
            PopulateProcess(Int32.Parse(ddlCategory.SelectedValue));
        }

        protected void ddlProcess_SelectedIndexChanged(object sender, EventArgs e)
        {
            ProcessRow row = CentralOffice.Admin.BusinessActions.ApprovalProcess.GetByIdFromCache(new Guid(ddlProcess.SelectedValue));
            

            SetPreProcess(row);
        }

        private void PopulateProcess(int approvalSubject)
        {
            ProcessTable processes = CentralOffice.Admin.BusinessActions.ApprovalProcess.GetProcessBySubject(approvalSubject);


            ddlProcess.Items.Clear();
            ddlProcess.DataSource = processes;
            ddlProcess.DataTextField = "Name";
            ddlProcess.DataValueField = "Id";
            ddlProcess.DataBind();

            if (processes.Rows.Count > 0)
            {
                ProcessRow row = processes.Rows[0] as ProcessRow;
                //ddlUrgencyDegree.SelectedValue = row.IsUrgencyDegreeNull()?"0": row.UrgencyDegree.ToString();
                //txtExecutor.Value = row.IsExecutorNull() ? "" : row.Executor;
                //txtExecutorReadOnly.Value = row.IsExecutorNull() ? "" : row.Executor;

                //txtExecutor.Text = row.Executor;

                SetPreProcess(row);
            }
        }

        private void SetPreProcess(ProcessRow row)
        {
            //ddlUrgencyDegree.SelectedValue = row.IsUrgencyDegreeNull() ? "0" : row.UrgencyDegree.ToString();
            //txtExecutor.Value = row.IsExecutorNull() ? "" : row.Executor;
            //txtExecutorReadOnly.Value = row.IsExecutorNull() ? "" : row.Executor;

            StepTable steps = CentralOffice.Admin.BusinessActions.ApprovalStep.GetStepByProcessId(row.Id);
            //StepRow step = steps.FirstOrDefault();
            //if (step != null)
            //{
            //    //txtApprovalContent.Text = step.ApprovalContent;
            //    //txtApprovedBy.Value = step.IsApprovalByEmpNull() ? "" : step.ApprovalByEmp;
            //    //txtApprovedByReadOnly.Value = step.IsApprovalByEmpNull() ? "" : step.ApprovalByEmp;
            //}

            txtExecutor.Text = row.Executor;

            gvStep.DataSource = steps;
            gvStep.DataBind();

        }

        private string SaveFile(string rootDir, FileUpload file)
        {
            string fileName = "";

            string path = Server.MapPath(rootDir);
            if (file.HasFile)
            {
                //file.SaveAs(path + file.FileName);
                //fileName = rootDir + file.FileName;
                var fn = SiteUtil.GetUploadFileName(path, file.FileName);
                file.SaveAs(fn);
                fileName = rootDir + fn.Substring(fn.LastIndexOf('\\') + 1);
            }
            else
            {

            }
            return fileName;
        }

        private void AddApprovalSteps(ApprovalDataSet approvalDataSet, Guid applicationId, ProcessRow process, StepTable steps)
        {
            //ProcessRow process = CentralOffice.Admin.BusinessActions.ApprovalProcess.GetByIdFromCache(new Guid(ddlProcess.SelectedValue));
            //StepTable steps = CentralOffice.Admin.BusinessActions.ApprovalStep.GetStepByProcessId(new Guid(ddlProcess.SelectedValue));
            string interval = SiteUtil.GetConfigurationItem(process.UrgencyDegree, SiteConstants.Priority).Data;
            

            int cnt = 1;
            Guid previousStepId = Guid.NewGuid();
            foreach (StepRow step in steps.Rows)
            {
                ApprovalRow approval = approvalDataSet.Approvals.NewApprovalsRow();
                SiteUtil.PopulateCommonField(approval, Guid.NewGuid());

                approval.ApplicationId = applicationId;
                approval.ApprovedBy = step.IsApprovalByEmpNull()?"":step.ApprovalByEmp;
                //approval.DateApproved = txtDateApproved.Text;
                if (cnt == 1 && txtContentText.Text.Length > 0)
                {
                    approval.ContentText = txtContentText.Text;
                }
                else
                {
                    approval.ContentText = step.ApprovalContent;
                    approval.CreatedTime = DateTime.Now.AddYears(1000);
                }
                //approval.Opinion = txtOpinion.Text;
                //approval.ResultApproved = txtResultApproved.Text;
                if (cnt != 1)
                {
                    approval.PreviousStep = previousStepId;
                }
                approval.IsFinal = (steps.Rows.Count == cnt);
                approval.NextStepIsApproved = false;
                approval.IsApproved = false;
                approval.SequenceNumber = cnt;
                approval.ElapsedTime = 0;
                approval.IsActive = cnt == 1;
                approval.StepId = step.Id;

                // 生成下一步的previousStepId
                previousStepId = approval.Id;


                //string interval = SiteUtil.GetConfigurationItem(step, SiteConstants.Priority).Data;
                approval.WarningDate = DateTime.Now.AddMinutes(Convert.ToDouble(interval));

                approvalDataSet.Approvals.AddApprovalsRow(approval);
                cnt++;
            }

        }
    }
}